﻿using System.Collections.Generic;
using UnityEngine;

public static partial class Extensions
{
    /// <summary>
    /// 数组浅拷贝
    /// </summary>
    public static List<T> Clone<T>(this List<T> list)
    {
        var newList = new List<T>();
        newList.AddRange(list);
        return newList;
    }

    /// <summary>
    /// 从数组中随机取一个元素
    /// </summary>
    public static T RandomElement<T>(this List<T> list)
    {
        if (list == null || list.Count <= 0)
        {
            Debug.LogError("no element in target list");
            return default(T);
        }
        return list[Random.Range(0, list.Count)];
    }

    /// <summary>
    /// 从数组中随机取出任意数量的不同元素
    /// </summary>
    public static List<T> RandomSubList<T>(this List<T> list, int count, bool coverSource = false)
    {
        if (!coverSource)
        {
            var newList = new List<T>();
            for (int i = 0; i < list.Count; i++)
            {
                newList.Add(list[i]);
            }
            list = newList;
        }
        if (count <= 0)
        {
            list.Clear();
            return list;
        }
        while (list.Count > count && list.Count > 0)
        {
            list.RemoveAt(Random.Range(0, list.Count));
        }
        return list;
    }

    /// <summary>
    /// 安全获取
    /// </summary>
    public static T GetSavely<T>(this List<T> list, int index)
    {
        if (list == null || list.Count == 0 || index >= list.Count) return default;
        return list[index];
    }

    /// <summary>
    /// 安全添加（值为int类型的计数类dict专用）
    /// </summary>
    public static void AddSavely<TKey>(this Dictionary<TKey, int> dict, TKey key, int count)
    {
        if (dict.ContainsKey(key))
        {
            dict[key] += count;
        }
        else
        {
            dict[key] = count;
        }
    }
}